<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { addTemporaryUser, getDepartmentWaitCount, getDepartmentBizCategory, getDepartmentCallInfo, takeNumber, printTicket, userLogin, faceLogin, submitBooking } from './api/tempUser.js'

const activePageId = ref('home-page')

// 用户身份管理 - 全局变量
const userId = ref('') // 登录用户ID
const terminalId = ref('') // 临时人员ID
const userIdNumber = ref('') // 用户身份证号
const userType = ref('') // 用户类型：'login' 或 'temporary'
const userDepartmentId = ref('') // 用户部门ID
const userToken = ref('') // 用户登录token

// 获取当前有效的用户标识
const getCurrentUserId = () => {
  if (userId.value) {
    return { userId: userId.value, type: 'login' }
  } else if (terminalId.value) {
    return { terminalId: terminalId.value, type: 'temporary' }
  }
  return { type: 'none' }
}

// 临时建档表单数据
const tempUserForm = ref({
  idNumber: '',
  name: '',
  phone: '',
  purpose: ''
})

// 表单提交状态
const isSubmitting = ref(false)
const submitMessage = ref('')

// 部门等候人数数据（包含departmentId）
const departmentWaitCounts = ref({})
const departmentList = ref([]) // 存储部门列表（包含departmentId）
const isLoadingCounts = ref(false)
let refreshTimer = null

// 选中的部门信息（包含departmentId）
const selectedDepartment = ref({
  id: '',
  name: '',
  description: ''
})

// 业务类型列表
const bizCategoryList = ref([])
const isLoadingBizCategory = ref(false)

// 登录表单数据
const loginForm = ref({
  username: '',
  password: '',
  idNumber: '',
  cardNumber: ''
})

// 登录状态
const isLoggingIn = ref(false)
const loginMessage = ref('')
const currentLoginType = ref('') // 当前登录类型

// 人脸识别状态
const isFaceScanning = ref(false)
const faceMessage = ref('')

// 数字键盘状态
const cardNumber = ref('')
const showCardLogin = ref(false)

// 叫号信息数据
const callInfo = ref({
  currentNumber: '',
  currentWindow: '',
  waitingList: [],
  userNumber: ''
})
const isLoadingCallInfo = ref(false)
let callInfoTimer = null

// 取号相关数据
const ticketInfo = ref({
  number: '',
  department: '',
  business: '',
  waitingCount: 0,
  estimatedWaitTime: 0,
  takeTime: ''
})
const isTakingNumber = ref(false)
const takeNumberMessage = ref('')

// 打印相关数据
const isPrinting = ref(false)
const printMessage = ref('')

// 语音提示相关数据
const voiceEnabled = ref(true)
const voiceVolume = ref(80)
const showVoiceModal = ref(false)

// 当前用户信息（用于兼容HTML版本的逻辑）
const currentUser = ref(null)

// 显示登录页面
function showLoginPage(loginType) {
  currentLoginType.value = loginType
  resetLoginForm()
  
  switch(loginType) {
    case 'face':
      activePageId.value = 'face-login-page'
      break
    case 'card':
      activePageId.value = 'card-login-page'
      cardNumber.value = ''
      break
    case 'id':
      activePageId.value = 'id-login-page'
      break
    case 'unified':
      activePageId.value = 'unified-login-page'
      break
  }
}

// 重置登录表单
function resetLoginForm() {
  loginForm.value = {
    username: '',
    password: '',
    idNumber: '',
    cardNumber: ''
  }
  loginMessage.value = ''
  faceMessage.value = ''
  isLoggingIn.value = false
  isFaceScanning.value = false
}

function showPage(pageId) {
  activePageId.value = pageId
  
  // 返回到首页时自动退出登录
  if (pageId === 'home-page') {
    logout()
  }
  
  // 切换页面时清空表单和消息
  if (pageId !== 'temp-register-page') {
    resetTempForm()
  }
  
  // 切换到部门页面时刷新等候人数
  if (pageId === 'department-page') {
    fetchDepartmentWaitCounts()
    stopCallInfoRefresh() // 停止叫号信息刷新
  }
  
  // 离开排队信息页面时停止叫号信息刷新
  if (pageId !== 'queue-info-page') {
    stopCallInfoRefresh()
  }
  
  // 清空取号和打印相关消息
  if (pageId !== 'ticket-page') {
    takeNumberMessage.value = ''
    printMessage.value = ''
  }
  
  // 播放页面语音提示
  playPageVoice(pageId)
}

function resetTempForm() {
  tempUserForm.value = {
    idNumber: '',
    name: '',
    phone: '',
    purpose: ''
  }
  submitMessage.value = ''
  isSubmitting.value = false
}

// 获取部门等候人数（包含departmentId）
async function fetchDepartmentWaitCounts() {
  try {
    isLoadingCounts.value = true
    const response = await getDepartmentWaitCount()
    
    // API返回格式修正 - 适配新的数据结构
    if (response && response.code === 200 && response.data && response.data.rows && Array.isArray(response.data.rows)) {
      departmentList.value = response.data.rows.map(dept => ({
        departmentId: dept.deptId,
        name: dept.deptName,
        waitCount: 0, // 新接口可能不包含等待人数，设为0
        description: dept.remark || '业务办理'
      }))
      // 转换为简单的 name: count 格式用于显示
      departmentWaitCounts.value = response.data.rows.reduce((acc, dept) => {
        acc[dept.deptName] = 0 // 新接口可能不包含等待人数，设为0
        return acc
      }, {})
    }
  } catch (error) {
    console.error('获取部门等候人数失败:', error)
    // 使用默认数据
    departmentList.value = [
      { departmentId: "DEPT001", name: "教务处", waitCount: 5, description: "学籍管理、成绩查询等" },
      { departmentId: "DEPT002", name: "学生处", waitCount: 3, description: "奖学金、助学金等" },
      { departmentId: "DEPT003", name: "财务处", waitCount: 8, description: "学费缴纳、发票打印等" },
      { departmentId: "DEPT004", name: "后勤处", waitCount: 2, description: "宿舍管理、校园卡等" },
      { departmentId: "DEPT005", name: "国际交流处", waitCount: 1, description: "留学申请、外事服务等" }
    ]
    departmentWaitCounts.value = {
      '教务处': 5,
      '学生处': 3,
      '财务处': 8,
      '后勤处': 2,
      '国际交流处': 1
    }
  } finally {
    isLoadingCounts.value = false
  }
}

// 启动自动刷新
function startAutoRefresh() {
  // 立即获取一次数据
  fetchDepartmentWaitCounts()
  
  // 每30秒自动刷新一次
  refreshTimer = setInterval(() => {
    if (activePageId.value === 'department-page') {
      fetchDepartmentWaitCounts()
    }
  }, 30000)
}

// 停止自动刷新
function stopAutoRefresh() {
  if (refreshTimer) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
}

// 选择部门（传入departmentId）
async function selectDepartment(departmentId, name, description) {
  selectedDepartment.value = { id: departmentId, name, description }
  
  // 获取该部门的业务类型列表
  await fetchBizCategoryList(departmentId)
  
  // 显示业务类型选择页面（如果有业务类型）或直接显示排队信息
  if (bizCategoryList.value.length > 0) {
    showPage('biz-category-page')
  } else {
    showPage('queue-info-page')
    // 立即获取叫号信息（传入terminalId和departmentId）
    fetchCallInfo()
    // 启动叫号信息自动刷新
    startCallInfoRefresh()
  }
}

// 获取部门的业务类型列表
async function fetchBizCategoryList(deptId) {
  try {
    isLoadingBizCategory.value = true
    const response = await getDepartmentBizCategory(deptId)
    
    // 处理返回的业务类型数据
    if (response && response.code === 200 && response.data && Array.isArray(response.data)) {
      bizCategoryList.value = response.data.map(item => ({
        dictCode: item.dictCode,
        dictLabel: item.dictLabel,
        dictValue: item.dictValue,
        dictSort: item.dictSort
      }))
    } else {
      bizCategoryList.value = []
    }
  } catch (error) {
    console.error('获取业务类型列表失败:', error)
    bizCategoryList.value = []
  } finally {
    isLoadingBizCategory.value = false
  }
}

// 选择业务类型
function selectBizCategory(bizCategory) {
  console.log('选择的业务类型:', bizCategory)
  // 这里可以添加业务类型选择的逻辑
  // 然后跳转到排队信息页面
  showPage('queue-info-page')
  // 立即获取叫号信息（传入terminalId和departmentId）
  fetchCallInfo()
  // 启动叫号信息自动刷新
  startCallInfoRefresh()
}

// 获取叫号信息（传入terminalId和departmentId）
async function fetchCallInfo() {
  try {
    isLoadingCallInfo.value = true
    const response = await getDepartmentCallInfo(terminalId.value, selectedDepartment.value.id)
    
    // API返回的数据格式
    if (response && response.data) {
      // 处理等待办理名单
      const waitingList = response.data.waitCalls ? response.data.waitCalls.map(item => ({
        number: item.ticketNo,
        waitTime: `${item.waitingDuration}分钟`
      })) : []
      
      callInfo.value = {
        currentNumber: response.data.currentTicketNo || '暂无',
        currentWindow: response.data.counterName || '暂无',
        waitingList: waitingList,
        userNumber: response.userNumber || '' // 如果没有用户号码，显示空字符串
      }
    }
  } catch (error) {
    console.error('获取叫号信息失败:', error)
    // 调用失败时显示空数据，不显示混淆性的默认值
    callInfo.value = {
      currentNumber: '暂无',
      currentWindow: '暂无',
      waitingList: [],
      userNumber: ''
    }
  } finally {
    isLoadingCallInfo.value = false
  }
}

// 启动叫号信息自动刷新
function startCallInfoRefresh() {
  // 每10秒刷新一次叫号信息
  callInfoTimer = setInterval(() => {
    if (activePageId.value === 'queue-info-page') {
      fetchCallInfo()
    }
  }, 10000)
}

// 停止叫号信息自动刷新
function stopCallInfoRefresh() {
  if (callInfoTimer) {
    clearInterval(callInfoTimer)
    callInfoTimer = null
  }
}

// 取号功能
async function handleTakeNumber() {
  isTakingNumber.value = true
  takeNumberMessage.value = '正在提交预约...'
  
  try {
    const currentUser = getCurrentUserId()
    
    // 检查用户身份
    if (!currentUser.userId && !currentUser.terminalId) {
      throw new Error('用户身份未确认，请重新登录')
    }
    
    // 生成取号信息
    ticketInfo.value = {
      number: `${selectedDepartment.value.name.charAt(0)}${String(Date.now()).slice(-3)}`,
      department: selectedDepartment.value.name,
      business: selectedDepartment.value.description,
      waitingCount: callInfo.value.waitingList.length,
      estimatedWaitTime: callInfo.value.waitingList.length * 5,
      takeTime: new Date().toLocaleString('zh-CN')
    }
    
    // 提交预约信息（仅对登录用户）
    if (currentUser.type === 'login' && currentUser.userId) {
      try {
        const bookingResponse = await submitBooking(currentUser.userId, selectedDepartment.value.name, userDepartmentId.value, userToken.value)
        console.log('预约信息提交成功:', bookingResponse)
        
        // 使用预约接口返回的ticketNo
        if (bookingResponse && bookingResponse.booking && bookingResponse.booking.ticketNo) {
          ticketInfo.value.number = bookingResponse.booking.ticketNo
        }
        
        takeNumberMessage.value = '预约提交成功！'
      } catch (bookingError) {
        console.error('预约信息提交失败:', bookingError)
        takeNumberMessage.value = '预约提交失败，请重试'
        throw bookingError
      }
    } else {
      console.log('临时用户或未登录用户，跳过预约提交')
      takeNumberMessage.value = '取号成功！'
    }
    
    // 更新叫号信息中的用户号码
    callInfo.value.userNumber = ticketInfo.value.number
    
    // 延迟跳转到小票页面
    setTimeout(() => {
      showPage('ticket-page')
    }, 1000)
    
  } catch (error) {
    takeNumberMessage.value = '操作失败，请重试'
    console.error('操作失败:', error)
    
    // 失败时使用默认数据
    ticketInfo.value = {
      number: `${selectedDepartment.value.name.charAt(0)}${String(Date.now()).slice(-3)}`,
      department: selectedDepartment.value.name,
      business: selectedDepartment.value.description,
      waitingCount: callInfo.value.waitingList.length,
      estimatedWaitTime: callInfo.value.waitingList.length * 5,
      takeTime: new Date().toLocaleString('zh-CN')
    }
    
    // 即使失败也跳转到小票页面（显示错误信息）
    setTimeout(() => {
      showPage('ticket-page')
    }, 2000)
  } finally {
    isTakingNumber.value = false
  }
}

// 打印小票功能
async function handlePrintTicket() {
  isPrinting.value = true
  printMessage.value = '正在打印...'
  
  try {
    const response = await printTicket()
    
    // API调用成功
    if (response) {
      printMessage.value = '打印成功！'
      
      // 打印成功后的操作
      console.log('打印响应:', response)
      
      // 3秒后清除消息
      setTimeout(() => {
        printMessage.value = ''
      }, 3000)
    }
  } catch (error) {
    printMessage.value = '打印失败，请联系工作人员'
    console.error('打印失败:', error)
    
    // 5秒后清除错误消息
    setTimeout(() => {
      printMessage.value = ''
    }, 5000)
  } finally {
    isPrinting.value = false
  }
}

// 统一认证登录
async function handleUnifiedLogin() {
  if (!loginForm.value.username || !loginForm.value.password) {
    loginMessage.value = '请输入用户名和密码'
    return
  }
  
  isLoggingIn.value = true
  loginMessage.value = '正在登录...'
  
  try {
    const response = await userLogin(loginForm.value.username, loginForm.value.password, 'unified')
    console.log('登录响应:', response) // 添加调试信息
    
    // 修改响应判断逻辑
    if (response && (response.code === 200 || response.success)) {
      // 设置登录用户信息 - 从response.user获取用户数据
      const userData = response.user || response.data || response
      
      // 检查是否返回了真实的用户ID
      if (userData && userData.id) {
        currentUser.value = {
          id: userData.id,
          name: userData.name || '用户',
          type: '统一认证'
        }
        setLoginUser(userData.id, userData.idNumber || userData.cardNumber || userData.phone || '', userData.departmentId, response.token)
        loginMessage.value = '登录成功！'
        
        setTimeout(() => {
          showPage('department-page')
        }, 1000)
      } else {
        loginMessage.value = '登录失败，未获取到用户信息'
        console.log('用户数据:', userData) // 添加调试信息
      }
    } else {
      // 如果API返回了响应但不是成功状态
      loginMessage.value = response.msg || response.message || '登录失败，请检查用户名和密码'
    }
  } catch (error) {
    console.error('统一认证登录失败:', error)
    loginMessage.value = '登录失败，请检查用户名和密码'
  } finally {
    isLoggingIn.value = false
  }
}

// 身份证登录
async function handleIdLogin() {
  if (!loginForm.value.idNumber) {
    loginMessage.value = '请输入身份证号码'
    return
  }
  
  if (loginForm.value.idNumber.length !== 18) {
    loginMessage.value = '请输入正确的18位身份证号码'
    return
  }
  
  isLoggingIn.value = true
  loginMessage.value = '正在验证身份证...'
  
  try {
    const response = await userLogin('', '', 'id', loginForm.value.idNumber)
    console.log('身份证登录响应:', response) // 添加调试信息
    
    if (response && (response.code === 200 || response.success)) {
      const userData = response.user || response.data || response
      
      // 检查是否返回了真实的用户ID
      if (userData && userData.id) {
        currentUser.value = {
          id: userData.id,
          name: userData.name || '用户',
          type: '身份证'
        }
        setLoginUser(userData.id, loginForm.value.idNumber, userData.departmentId, response.token)
        loginMessage.value = '身份证验证成功！'
        
        setTimeout(() => {
          showPage('department-page')
        }, 1000)
      } else {
        loginMessage.value = '身份证验证失败，未获取到用户信息'
        console.log('用户数据:', userData) // 添加调试信息
      }
    } else {
      loginMessage.value = response.msg || response.message || '身份证验证失败，请重试'
    }
  } catch (error) {
    console.error('身份证登录失败:', error)
    loginMessage.value = '身份证验证失败，请重试'
  } finally {
    isLoggingIn.value = false
  }
}

// 一卡通登录
async function handleCardLogin() {
  if (!loginForm.value.cardNumber) {
    loginMessage.value = '请输入一卡通号码'
    return
  }
  
  isLoggingIn.value = true
  loginMessage.value = '正在验证一卡通...'
  
  try {
    const response = await userLogin('', '', 'card', '', loginForm.value.cardNumber)
    console.log('一卡通登录响应:', response) // 添加调试信息
    
    if (response && (response.code === 200 || response.success)) {
      const userData = response.user || response.data || response
      
      // 检查是否返回了真实的用户ID
      if (userData && userData.id) {
        currentUser.value = {
          id: userData.id,
          name: userData.name || '用户',
          type: '一卡通'
        }
        setLoginUser(userData.id, userData.idNumber || userData.cardNumber || userData.phone || '', userData.departmentId, response.token)
        loginMessage.value = '一卡通验证成功！'
        
        setTimeout(() => {
          showPage('department-page')
        }, 1000)
      } else {
        loginMessage.value = '一卡通验证失败，未获取到用户信息'
        console.log('用户数据:', userData) // 添加调试信息
      }
    } else {
      loginMessage.value = response.msg || response.message || '一卡通验证失败，请重试'
    }
  } catch (error) {
    console.error('一卡通登录失败:', error)
    loginMessage.value = '一卡通验证失败，请重试'
  } finally {
    isLoggingIn.value = false
  }
}

// 人脸识别登录
async function handleFaceLogin() {
  isFaceScanning.value = true
  faceMessage.value = '请面向摄像头，正在进行人脸识别...'
  
  try {
    // 模拟人脸识别过程
    await new Promise(resolve => setTimeout(resolve, 3000))
    
    // 这里应该获取人脸数据，暂时用模拟数据
    const faceData = 'simulated_face_data'
    const response = await faceLogin(faceData)
    console.log('人脸识别响应:', response) // 添加调试信息
    
    if (response && (response.code === 200 || response.success)) {
      const userData = response.user || response.data || response
      
      // 检查是否返回了真实的用户ID
      if (userData && userData.id) {
        currentUser.value = {
          id: userData.id,
          name: userData.name || '用户',
          type: '人脸识别'
        }
        setLoginUser(userData.id, userData.idNumber || userData.phone || '', userData.departmentId, response.token)
        faceMessage.value = '人脸识别成功！'
        
        setTimeout(() => {
          showPage('department-page')
        }, 1000)
      } else {
        faceMessage.value = '人脸识别失败，未获取到用户信息'
        console.log('用户数据:', userData) // 添加调试信息
      }
    } else {
      faceMessage.value = response.msg || response.message || '人脸识别失败，请重试'
    }
  } catch (error) {
    console.error('人脸识别登录失败:', error)
    faceMessage.value = '人脸识别失败，请重试'
  } finally {
    isFaceScanning.value = false
  }
}

// 设置登录用户信息
function setLoginUser(loginUserId, idNumber, departmentId, token) {
  console.log('设置用户信息:', { loginUserId, idNumber, departmentId, token }) // 添加调试信息
  
  userId.value = loginUserId
  userIdNumber.value = idNumber
  userDepartmentId.value = departmentId || ''
  userToken.value = token || ''
  userType.value = 'login'
  // 清空terminalId确保只有一个有效
  terminalId.value = ''
  
  // 存储到localStorage
  localStorage.setItem('userId', loginUserId)
  localStorage.setItem('userType', 'login')
  localStorage.setItem('userIdNumber', idNumber)
  localStorage.setItem('userDepartmentId', departmentId || '')
  localStorage.setItem('userToken', token || '')
  
  console.log('用户信息已设置，当前状态:', {
    userId: userId.value,
    userType: userType.value,
    userIdNumber: userIdNumber.value,
    userDepartmentId: userDepartmentId.value,
    userToken: userToken.value
  })
}

// 组件挂载时启动自动刷新
onMounted(() => {
  // 从localStorage恢复用户状态
  const savedUserType = localStorage.getItem('userType')
  const savedIdNumber = localStorage.getItem('userIdNumber')
  
  if (savedUserType === 'login') {
    userId.value = localStorage.getItem('userId') || ''
    userType.value = 'login'
    userDepartmentId.value = localStorage.getItem('userDepartmentId') || ''
    userToken.value = localStorage.getItem('userToken') || ''
    // 恢复currentUser
    currentUser.value = {
      id: localStorage.getItem('userId') || '',
      name: '用户',
      type: '已登录'
    }
  } else if (savedUserType === 'temporary') {
    terminalId.value = localStorage.getItem('terminalId') || ''
    userType.value = 'temporary'
    // 恢复currentUser
    currentUser.value = {
      id: localStorage.getItem('terminalId') || '',
      name: '临时用户',
      type: '临时访客'
    }
  }
  
  userIdNumber.value = savedIdNumber || ''
  
  startAutoRefresh()
  
  // 页面加载时播放欢迎语音
  setTimeout(() => {
    speak('欢迎使用学校智能服务大厅自助叫号系统')
  }, 1000)
})

// 组件卸载时停止自动刷新
onUnmounted(() => {
  stopAutoRefresh()
  stopCallInfoRefresh()
})

// 语音提示功能
function speak(text) {
  if (!voiceEnabled.value || !text) return
  
  if ('speechSynthesis' in window) {
    const utterance = new SpeechSynthesisUtterance(text)
    utterance.lang = 'zh-CN'
    utterance.volume = voiceVolume.value / 100
    window.speechSynthesis.speak(utterance)
  }
}

// 播放页面语音提示
function playPageVoice(pageId) {
  if (!voiceEnabled.value) return
  
  const messages = {
    'home-page': '欢迎使用学校智能服务大厅，请选择您需要的服务',
    'department-page': '请选择您要办理的业务部门',
    'biz-category-page': `请选择${selectedDepartment.value.name}的业务类型`,
    'queue-info-page': `当前排队情况，${selectedDepartment.value.name}当前办理号码${callInfo.value.currentNumber}，您的号码是${callInfo.value.userNumber}`,
    'ticket-page': `取号成功，您的号码是${ticketInfo.value.number}，前面等待${ticketInfo.value.waitingCount}人，预计等待时间${ticketInfo.value.estimatedWaitTime}分钟，请妥善保管您的号码`,
    'temp-register-page': '请填写临时人员信息',
    'blacklist-page': '系统提示，您的线上预约权限已暂停'
  }
  
  if (messages[pageId]) {
    setTimeout(() => speak(messages[pageId]), 500)
  }
}

// 切换语音模态框
function toggleVoiceModal() {
  showVoiceModal.value = !showVoiceModal.value
}

// 关闭语音模态框
function closeVoiceModal() {
  showVoiceModal.value = false
}

// 测试语音
function testVoice() {
  speak('这是语音提示测试，当前音量设置测试')
}

// 根据等待人数返回样式类
function getWaitingNumberClass(count) {
  if (count === 0) return 'low'
  if (count <= 3) return 'low'
  if (count <= 6) return 'medium'
  return 'high'
}

// 学生业务办理 - 跳转到登录界面
function handleStudentService() {
  // 设置学生业务办理标识
  currentLoginType.value = 'student'
  // 跳转到登录页面
  showPage('login-page')
}

// 退出登录
function logout() {
  // 清空用户信息
  currentUser.value = null
  userId.value = ''
  terminalId.value = ''
  userIdNumber.value = ''
  userDepartmentId.value = ''
  userToken.value = ''
  userType.value = ''
  
  // 清空localStorage
  localStorage.removeItem('userId')
  localStorage.removeItem('terminalId')
  localStorage.removeItem('userType')
  localStorage.removeItem('userIdNumber')
  localStorage.removeItem('userDepartmentId')
  localStorage.removeItem('userToken')
  
  // 清空登录相关状态
  loginMessage.value = ''
  isLoggingIn.value = false
  
  console.log('用户已退出登录')
}

// 显示部门选择页面
function showDepartmentPage() {
  // 检查是否已登录
  if (!currentUser.value) {
    showPage('login-page')
    return
  }
  
  showPage('department-page')
}


// 数字键盘功能
function appendNumber(num) {
  cardNumber.value += num
}

function clearNumber() {
  cardNumber.value = cardNumber.value.slice(0, -1)
}

function clearAllNumbers() {
  cardNumber.value = ''
}

function submitCardNumber() {
  if (!cardNumber.value) {
    loginMessage.value = '请输入一卡通号码'
    return
  }
  
  isLoggingIn.value = true
  loginMessage.value = '正在验证一卡通...'
  
  // 模拟登录过程
  setTimeout(() => {
    // 登录成功
    currentUser.value = {
      id: cardNumber.value,
      name: '学生用户',
      type: '一卡通'
    }
    setLoginUser('card_' + Date.now(), cardNumber.value)
    loginMessage.value = '一卡通验证成功！'
    speak(`登录成功，欢迎${currentUser.value.name}`)
    
    setTimeout(() => {
      showPage('department-page')
      cardNumber.value = ''
    }, 1000)
  }, 2000)
}

// 提交临时建档
async function submitTempRegistration() {
  // 表单验证
  if (!tempUserForm.value.idNumber || !tempUserForm.value.name || !tempUserForm.value.phone) {
    submitMessage.value = '请填写完整信息'
    return
  }
  
  // 简单的身份证号验证
  if (tempUserForm.value.idNumber.length !== 18) {
    submitMessage.value = '请输入正确的18位身份证号码'
    return
  }
  
  // 简单的手机号验证
  if (!/^1[3-9]\d{9}$/.test(tempUserForm.value.phone)) {
    submitMessage.value = '请输入正确的11位手机号码'
    return
  }
  
  isSubmitting.value = true
  submitMessage.value = '正在提交...'
  
  try {
    const result = await addTemporaryUser(tempUserForm.value)
    
    // 保存临时人员ID和相关信息
    if (result && result.data && result.data.terminalId) {
      currentUser.value = {
        id: result.data.terminalId,
        name: tempUserForm.value.name,
        type: '临时访客'
      }
      terminalId.value = result.data.terminalId
      userIdNumber.value = tempUserForm.value.idNumber
      userType.value = 'temporary'
      // 清空userId确保只有一个有效
      userId.value = ''
      
      // 存储到localStorage作为备份
      localStorage.setItem('terminalId', result.data.terminalId)
      localStorage.setItem('userType', 'temporary')
      localStorage.setItem('userIdNumber', tempUserForm.value.idNumber)
      console.log('临时人员ID:', result.data.terminalId)
    }
    
    submitMessage.value = '建档成功！'
    
    // 延迟跳转到部门选择页
    setTimeout(() => {
      showPage('department-page')
    }, 1500)
    
  } catch (error) {
    submitMessage.value = '建档失败，请重试'
    console.error('建档失败:', error)
  } finally {
    isSubmitting.value = false
  }
}
</script>

<template>
  <!-- 语音提示按钮 -->
  <div class="voice-notification" @click="toggleVoiceModal" :class="{ active: !voiceEnabled }">
    <i class="fas fa-volume-up"></i>
  </div>
  
  <!-- 语音设置弹窗 -->
  <div class="voice-modal" :class="{ active: showVoiceModal }" @click="closeVoiceModal">
    <div class="voice-modal-content" @click.stop>
      <h3><i class="fas fa-volume-up"></i> 语音提示设置</h3>
      <p>您可以根据需要调整语音提示的音量和开关</p>
      
      <div class="form-group" style="margin-top: 20px;">
        <label for="voice-volume">音量大小</label>
        <input type="range" id="voice-volume" min="0" max="100" v-model="voiceVolume">
      </div>
      
      <div class="form-group">
        <label style="display: flex; align-items: center; cursor: pointer;">
          <input type="checkbox" v-model="voiceEnabled" style="margin-right: 10px;">
          启用语音提示
        </label>
      </div>
      
      <div class="voice-options">
        <button class="btn btn-secondary" @click="closeVoiceModal">
          <i class="fas fa-times"></i> 关闭
        </button>
        <button class="btn" @click="testVoice">
          <i class="fas fa-play"></i> 测试语音
        </button>
      </div>
    </div>
  </div>

  <div class="container">
    <!-- 首页/登录页 -->
    <div id="home-page" class="page" :class="{ active: activePageId === 'home-page' }">
      <header>
        <h1>学校智能服务大厅</h1>
        <div class="subtitle">欢迎使用自助叫号系统</div>
      </header>

      <div class="login-options">
        <a href="#" class="login-btn" @click.prevent="handleStudentService()">
          <i class="fas fa-user-graduate"></i>
          <span>学生业务办理</span>
        </a>

        <a href="#" class="login-btn" @click.prevent="showDepartmentPage()">
          <i class="fas fa-chalkboard-teacher"></i>
          <span>教师业务办理</span>
        </a>

        <a href="#" class="login-btn" @click.prevent="showPage('temp-register-page')">
          <i class="fas fa-user-plus"></i>
          <span>临时人员建档</span>
        </a>

      </div>

      <div class="footer">
        <p>技术支持：学校信息中心</p>
        <p>服务电话：1234-567890</p>
      </div>
    </div>

    <!-- 登录方式选择页 -->
    <div id="login-page" class="page" :class="{ active: activePageId === 'login-page' }">
      <div class="login-logo">
        <i class="fas fa-user-shield"></i>
      </div>
      
      <div class="login-page">
        <h2>请选择登录方式</h2>
        
        <div class="login-options">
          <a href="#" class="login-btn" @click.prevent="showLoginPage('face')">
            <i class="fas fa-user-circle"></i>
            <span>人脸识别登录</span>
          </a>
          
          <a href="#" class="login-btn" @click.prevent="showLoginPage('card')">
            <i class="fas fa-id-card"></i>
            <span>一卡通登录</span>
          </a>
          
          <a href="#" class="login-btn" @click.prevent="showLoginPage('id')">
            <i class="fas fa-address-card"></i>
            <span>身份证登录</span>
          </a>
          
          <a href="#" class="login-btn" @click.prevent="showLoginPage('unified')">
            <i class="fas fa-key"></i>
            <span>统一认证登录</span>
          </a>
        </div>
        
        <div class="progress-container" v-show="isLoggingIn" style="margin-top: 20px;">
          <div class="progress-bar" :style="{ width: isLoggingIn ? '100%' : '0%' }"></div>
        </div>
        
        <button class="btn btn-secondary" @click="showPage('home-page')" style="width: 100%; margin-top: 20px;">
          <i class="fas fa-arrow-left"></i> 返回
        </button>
      </div>
    </div>

    <!-- 人脸识别登录页 -->
    <div id="face-login-page" class="page" :class="{ active: activePageId === 'face-login-page' }">
      <header>
        <h1>人脸识别登录</h1>
        <div class="subtitle">请面向摄像头进行人脸识别</div>
      </header>

      <div class="face-recognition">
        <div class="camera-area">
          <div class="camera-placeholder" :class="{ 'scanning': isFaceScanning }">
            <i class="fas fa-camera" v-if="!isFaceScanning"></i>
            <i class="fas fa-spinner fa-spin" v-else></i>
            <p v-if="!isFaceScanning">点击开始人脸识别</p>
            <p v-else>正在识别中...</p>
          </div>
        </div>
        
        <div v-if="faceMessage" class="face-message" :class="{ 'success': faceMessage.includes('成功'), 'error': faceMessage.includes('失败') }">
          {{ faceMessage }}
        </div>
        
        <button 
          class="login-submit-btn" 
          @click="handleFaceLogin"
          :disabled="isFaceScanning"
        >
          <i class="fas fa-spinner fa-spin" v-if="isFaceScanning"></i>
          <i class="fas fa-user-circle" v-else></i>
          {{ isFaceScanning ? '识别中...' : '开始人脸识别' }}
        </button>
      </div>

      <button class="btn btn-secondary" @click="showPage('login-page')" style="width: 100%; margin-top: 20px;">
        <i class="fas fa-arrow-left"></i> 返回
      </button>
    </div>

    <!-- 一卡通登录页 -->
    <div id="card-login-page" class="page" :class="{ active: activePageId === 'card-login-page' }">
      <header>
        <h1>一卡通登录</h1>
        <div class="subtitle">请输入您的一卡通号码</div>
      </header>

      <div class="login-page">
        <div class="numpad-display">
          {{ cardNumber || '请输入卡号' }}
        </div>
        
        <div class="numpad-container">
          <button class="numpad-btn" @click="appendNumber('1')">1</button>
          <button class="numpad-btn" @click="appendNumber('2')">2</button>
          <button class="numpad-btn" @click="appendNumber('3')">3</button>
          <button class="numpad-btn" @click="appendNumber('4')">4</button>
          <button class="numpad-btn" @click="appendNumber('5')">5</button>
          <button class="numpad-btn" @click="appendNumber('6')">6</button>
          <button class="numpad-btn" @click="appendNumber('7')">7</button>
          <button class="numpad-btn" @click="appendNumber('8')">8</button>
          <button class="numpad-btn" @click="appendNumber('9')">9</button>
          <button class="numpad-btn" @click="clearNumber()"><i class="fas fa-backspace"></i></button>
          <button class="numpad-btn" @click="appendNumber('0')">0</button>
          <button class="numpad-btn" @click="submitCardNumber()" style="background-color: var(--primary-color); color: white;" :disabled="isLoggingIn">
            <i class="fas fa-check" v-if="!isLoggingIn"></i>
            <i class="fas fa-spinner fa-spin" v-else></i>
          </button>
        </div>
        
        <div v-if="loginMessage" class="login-message" :class="{ 'success': loginMessage.includes('成功'), 'error': loginMessage.includes('失败') }">
          {{ loginMessage }}
        </div>
        
        <button class="btn btn-secondary" @click="showPage('login-page')" style="width: 100%; margin-top: 20px;">
          <i class="fas fa-arrow-left"></i> 返回
        </button>
      </div>
    </div>

    <!-- 身份证登录页 -->
    <div id="id-login-page" class="page" :class="{ active: activePageId === 'id-login-page' }">
      <header>
        <h1>身份证登录</h1>
        <div class="subtitle">请输入您的身份证号码</div>
      </header>

      <div class="login-form">
        <div class="form-group">
          <label for="id-number-login">身份证号码</label>
          <input 
            type="text" 
            id="id-number-login" 
            v-model="loginForm.idNumber"
            placeholder="请输入18位身份证号码"
            maxlength="18"
            :disabled="isLoggingIn"
            @keyup.enter="handleIdLogin"
          >
        </div>
        
        <div v-if="loginMessage" class="login-message" :class="{ 'success': loginMessage.includes('成功'), 'error': loginMessage.includes('失败') }">
          {{ loginMessage }}
        </div>
        
        <button 
          class="login-submit-btn" 
          @click="handleIdLogin"
          :disabled="isLoggingIn"
        >
          <i class="fas fa-spinner fa-spin" v-if="isLoggingIn"></i>
          <i class="fas fa-address-card" v-else></i>
          {{ isLoggingIn ? '验证中...' : '确认登录' }}
        </button>
      </div>

      <button class="btn btn-secondary" @click="showPage('login-page')" style="width: 100%; margin-top: 20px;">
        <i class="fas fa-arrow-left"></i> 返回
      </button>
    </div>

    <!-- 统一认证登录页 -->
    <div id="unified-login-page" class="page" :class="{ active: activePageId === 'unified-login-page' }">
      <header>
        <h1>统一认证登录</h1>
        <div class="subtitle">请输入您的用户名和密码</div>
      </header>

      <div class="login-form">
        <div class="form-group">
          <label for="username">用户名</label>
          <input 
            type="text" 
            id="username" 
            v-model="loginForm.username"
            placeholder="请输入用户名"
            :disabled="isLoggingIn"
          >
        </div>
        
        <div class="form-group">
          <label for="password">密码</label>
          <input 
            type="password" 
            id="password" 
            v-model="loginForm.password"
            placeholder="请输入密码"
            :disabled="isLoggingIn"
            @keyup.enter="handleUnifiedLogin"
          >
        </div>
        
        <div v-if="loginMessage" class="login-message" :class="{ 'success': loginMessage.includes('成功'), 'error': loginMessage.includes('失败') }">
          {{ loginMessage }}
        </div>
        
        <button 
          class="login-submit-btn" 
          @click="handleUnifiedLogin"
          :disabled="isLoggingIn"
        >
          <i class="fas fa-spinner fa-spin" v-if="isLoggingIn"></i>
          <i class="fas fa-key" v-else></i>
          {{ isLoggingIn ? '登录中...' : '确认登录' }}
        </button>
      </div>

      <button class="btn btn-secondary" @click="showPage('login-page')" style="width: 100%; margin-top: 20px;">
        <i class="fas fa-arrow-left"></i> 返回
      </button>
    </div>

    <!-- 部门选择页 -->
    <div id="department-page" class="page" :class="{ active: activePageId === 'department-page' }">
      <header>
        <h1>请选择办理部门</h1>
        <div class="subtitle">请选择您要办理的业务部门</div>
      </header>

      <div class="department-list">
        <!-- 动态渲染部门列表 -->
        <div 
          v-for="dept in departmentList" 
          :key="dept.departmentId"
          class="department-item" 
          @click="selectDepartment(dept.departmentId, dept.name, dept.description)"
        >
          <div>
            <h3>{{ dept.name }}</h3>
            <p>{{ dept.description }}</p>
          </div>
        </div>
        
        <!-- 如果没有部门数据，显示默认列表 -->
        <template v-if="departmentList.length === 0 && !isLoadingCounts">
          <div class="department-item" @click="selectDepartment('DEPT001', '教务处', '学籍管理、成绩查询等')">
            <div>
              <h3>教务处</h3>
              <p>学籍管理、成绩查询等</p>
            </div>
          </div>
          
          <div class="department-item" @click="selectDepartment('DEPT002', '学生处', '奖学金、助学金等')">
            <div>
              <h3>学生处</h3>
              <p>奖学金、助学金等</p>
            </div>
          </div>
          
          <div class="department-item" @click="selectDepartment('DEPT003', '财务处', '学费缴纳、发票打印等')">
            <div>
              <h3>财务处</h3>
              <p>学费缴纳、发票打印等</p>
            </div>
          </div>
          
          <div class="department-item" @click="selectDepartment('DEPT004', '后勤处', '宿舍管理、校园卡等')">
            <div>
              <h3>后勤处</h3>
              <p>宿舍管理、校园卡等</p>
            </div>
          </div>
          
          <div class="department-item" @click="selectDepartment('DEPT005', '国际交流处', '留学申请、外事服务等')">
            <div>
              <h3>国际交流处</h3>
              <p>留学申请、外事服务等</p>
            </div>
          </div>
          
          <div class="department-item" @click="selectDepartment('DEPT006', '图书馆', '借阅证办理、图书查询等')">
            <div>
              <h3>图书馆</h3>
              <p>借阅证办理、图书查询等</p>
            </div>
          </div>
        </template>
      </div>

      <div style="display: flex; gap: 10px; margin-top: 20px;">
        <button class="btn" @click="fetchDepartmentWaitCounts()" style="flex: 1;" :disabled="isLoadingCounts">
          <i class="fas fa-sync-alt" :class="{ 'fa-spin': isLoadingCounts }"></i> 
          {{ isLoadingCounts ? '刷新中...' : '刷新人数' }}
        </button>
        <button class="btn btn-secondary" @click="showPage('home-page')" style="flex: 1;">
          <i class="fas fa-arrow-left"></i> 返回首页
        </button>
      </div>
    </div>

    <!-- 业务类型选择页 -->
    <div id="biz-category-page" class="page" :class="{ active: activePageId === 'biz-category-page' }">
      <header>
        <h1>{{ selectedDepartment.name }} - 业务类型</h1>
        <div class="subtitle">请选择您要办理的业务类型</div>
      </header>

      <div class="biz-category-list">
        <!-- 动态渲染业务类型列表 -->
        <div 
          v-for="category in bizCategoryList" 
          :key="category.dictCode"
          class="biz-category-item" 
          @click="selectBizCategory(category)"
        >
          <div>
            <h3>{{ category.dictLabel }}</h3>
            <p>业务类型代码: {{ category.dictValue }}</p>
          </div>
          <div class="arrow">
            <i class="fas fa-chevron-right"></i>
          </div>
        </div>
        
        <!-- 如果没有业务类型数据，显示加载状态 -->
        <div v-if="isLoadingBizCategory" class="loading-indicator">
          <i class="fas fa-spinner fa-spin"></i>
          <p>正在加载业务类型...</p>
        </div>
        
        <!-- 如果没有业务类型数据且不在加载中，显示提示 -->
        <div v-else-if="bizCategoryList.length === 0" class="no-data">
          <i class="fas fa-info-circle"></i>
          <p>暂无业务类型数据</p>
        </div>
      </div>

      <div style="display: flex; gap: 10px; margin-top: 20px;">
        <button class="btn btn-secondary" @click="showPage('department-page')" style="flex: 1;">
          <i class="fas fa-arrow-left"></i> 返回部门选择
        </button>
        <button class="btn" @click="selectBizCategory(null)" style="flex: 1;">
          <i class="fas fa-forward"></i> 跳过，直接查看排队
        </button>
      </div>
    </div>

    <!-- 排队信息页 -->
    <div id="queue-info-page" class="page" :class="{ active: activePageId === 'queue-info-page' }">
      <header>
        <h1>{{ selectedDepartment.name }} - 排队信息</h1>
        <div class="subtitle">{{ selectedDepartment.description }}</div>
      </header>

      <div class="queue-info">
        <div class="current-number" :class="{ 'loading': isLoadingCallInfo }">
          <h2>当前办理号码</h2>
          <div v-if="isLoadingCallInfo" class="loading-indicator">
            <i class="fas fa-spinner fa-spin"></i>
            <p>获取叫号信息中...</p>
          </div>
          <div v-else>
            <span class="number">{{ callInfo.currentNumber }}</span>
            <p>{{ callInfo.currentWindow }}</p>
          </div>
        </div>

        <div style="display: flex; justify-content: space-between; align-items: center; margin: 20px 0 10px 0;">
          <h3>等待办理名单</h3>
          <button 
            class="refresh-btn" 
            @click="fetchCallInfo()" 
            :disabled="isLoadingCallInfo"
            title="刷新叫号信息"
          >
            <i class="fas fa-sync-alt" :class="{ 'fa-spin': isLoadingCallInfo }"></i>
          </button>
        </div>
        
        <div class="queue-list">
          <div v-if="isLoadingCallInfo" class="queue-item loading-item">
            <i class="fas fa-spinner fa-spin"></i>
            <span>加载中...</span>
          </div>
          <template v-else>
            <div v-for="item in callInfo.waitingList" :key="item.number" class="queue-item">
              <span>{{ item.number }}</span>
              <span>预计等待: {{ item.waitTime }}</span>
            </div>
            <div v-if="callInfo.userNumber" class="queue-item highlight">
              <span>{{ callInfo.userNumber }}</span>
              <span>您的号码</span>
            </div>
            <div v-if="callInfo.waitingList.length === 0 && !callInfo.userNumber" class="queue-item">
              <span style="color: #999;">暂无等待办理的号码</span>
            </div>
          </template>
        </div>
      </div>

      <!-- 取号消息显示 -->
      <div v-if="takeNumberMessage" class="take-number-message" :class="{ 'success': takeNumberMessage.includes('成功'), 'error': takeNumberMessage.includes('失败') }">
        {{ takeNumberMessage }}
      </div>

      <div style="display: flex; gap: 10px;">
        <button 
          class="btn" 
          @click="handleTakeNumber"
          :disabled="isTakingNumber"
        >
          <i class="fas fa-spinner fa-spin" v-if="isTakingNumber"></i>
          <i class="fas fa-print" v-else></i>
          {{ isTakingNumber ? '取号中...' : '确认取号' }}
        </button>

        <button class="btn btn-secondary" @click="showPage('department-page')">
          <i class="fas fa-arrow-left"></i> 返回
        </button>
      </div>
    </div>

    <!-- 取号成功页 -->
    <div id="ticket-page" class="page" :class="{ active: activePageId === 'ticket-page' }">
      <header>
        <h1>取号成功</h1>
        <div class="subtitle">请妥善保管您的号码</div>
      </header>

      <div class="ticket">
        <h2>学校智能服务大厅</h2>
        <div class="ticket-info">
          <div><strong>号码:</strong> {{ ticketInfo.number }}</div>
          <div><strong>部门:</strong> {{ ticketInfo.department }}</div>
          <div><strong>业务:</strong> {{ ticketInfo.business }}</div>
          <div><strong>取号时间:</strong> {{ ticketInfo.takeTime }}</div>
        </div>
        <p>请留意大屏幕叫号信息</p>
        
        <!-- 取号状态显示 -->
        <div v-if="takeNumberMessage.includes('失败')" class="ticket-error">
          <i class="fas fa-exclamation-triangle"></i>
          <p>网络取号失败，但已生成临时号码</p>
          <p>请到服务台确认或重新取号</p>
        </div>
      </div>

      <!-- 打印状态消息显示 -->
      <div v-if="printMessage" class="print-message" :class="{ 'success': printMessage.includes('成功'), 'error': printMessage.includes('失败') }">
        {{ printMessage }}
      </div>

      <div style="display: flex; gap: 10px;">
        <button 
          class="btn" 
          @click="handlePrintTicket"
          :disabled="isPrinting"
        >
          <i class="fas fa-spinner fa-spin" v-if="isPrinting"></i>
          <i class="fas fa-print" v-else></i>
          {{ isPrinting ? '打印中...' : '打印小票' }}
        </button>

        <button class="btn btn-secondary" @click="showPage('home-page')">
          <i class="fas fa-home"></i> 返回首页
        </button>
      </div>
    </div>

    <!-- 临时建档页 -->
    <div id="temp-register-page" class="page" :class="{ active: activePageId === 'temp-register-page' }">
      <header>
        <h1>临时人员建档</h1>
        <div class="subtitle">请填写您的信息</div>
      </header>

      <div class="form-group">
        <label for="id-number">身份证号码 *</label>
        <input 
          type="text" 
          id="id-number" 
          v-model="tempUserForm.idNumber"
          placeholder="请输入18位身份证号码"
          maxlength="18"
          :disabled="isSubmitting"
        >
      </div>

      <div class="form-group">
        <label for="name">姓名 *</label>
        <input 
          type="text" 
          id="name" 
          v-model="tempUserForm.name"
          placeholder="请输入您的姓名"
          :disabled="isSubmitting"
        >
      </div>

      <div class="form-group">
        <label for="phone">手机号码 *</label>
        <input 
          type="text" 
          id="phone" 
          v-model="tempUserForm.phone"
          placeholder="请输入11位手机号码"
          maxlength="11"
          :disabled="isSubmitting"
        >
      </div>

      <div class="form-group">
        <label for="purpose">办事目的</label>
        <textarea 
          id="purpose" 
          v-model="tempUserForm.purpose"
          placeholder="请简要描述您的办事目的（可选）"
          rows="3"
          :disabled="isSubmitting"
        ></textarea>
      </div>

      <!-- 提交消息显示 -->
      <div v-if="submitMessage" class="submit-message" :class="{ 'success': submitMessage.includes('成功'), 'error': submitMessage.includes('失败') }">
        {{ submitMessage }}
      </div>

      <button 
        class="submit-btn" 
        @click="submitTempRegistration"
        :disabled="isSubmitting"
      >
        <i class="fas fa-spinner fa-spin" v-if="isSubmitting"></i>
        {{ isSubmitting ? '提交中...' : '确认建档并取号' }}
      </button>

      <button 
        class="btn btn-secondary" 
        @click="showPage('home-page')" 
        style="width: 100%; margin-top: 10px;"
        :disabled="isSubmitting"
      >
        <i class="fas fa-times"></i> 取消返回
      </button>
    </div>

    <!-- 黑名单提示页 -->
    <div id="blacklist-page" class="page" :class="{ active: activePageId === 'blacklist-page' }">
      <header>
        <h1>系统提示</h1>
        <div class="subtitle">操作受限通知</div>
      </header>

      <div class="warning-box">
        <h2><i class="fas fa-exclamation-triangle"></i> 线上预约权限已暂停</h2>
        <p>由于您有3次预约后未按时到达的记录，系统已暂停您的线上预约权限（有效期7天）。</p>
        <p>您仍可前往服务大厅使用线下取号功能办理业务。</p>
        <p>如有疑问，请联系服务大厅工作人员。</p>

        <a href="#" class="back-btn" @click.prevent="showPage('home-page')">
          <i class="fas fa-arrow-left"></i> 返回首页
        </a>
      </div>
    </div>
  </div>
</template>

<style>
:root {
  --primary-color: #1a56a7;
  --primary-light: #e6f0ff;
  --secondary-color: #ff6b35;
  --success-color: #28a745;
  --warning-color: #ffc107;
  --danger-color: #dc3545;
  --dark-color: #343a40;
  --light-color: #f8f9fa;
  --border-radius: 10px;
  --box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  --transition: all 0.3s ease;
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Noto Sans SC', 'Microsoft YaHei', Arial, sans-serif;
}

body {
  background-color: #f5f5f5;
  color: #333;
  line-height: 1.6;
}

.container {
  max-width: 768px;
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
  min-height: 100vh;
  box-shadow: var(--box-shadow);
}

header {
  background: linear-gradient(135deg, var(--primary-color), #0d47a1);
  color: white;
  padding: 20px 0;
  text-align: center;
  margin-bottom: 20px;
  border-radius: var(--border-radius);
  position: relative;
  overflow: hidden;
}

header::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, transparent, rgba(255,255,255,0.7), transparent);
}

h1 {
  font-size: 28px;
  margin-bottom: 5px;
  font-weight: 700;
}

.subtitle {
  font-size: 14px;
  opacity: 0.9;
}

.login-options {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 15px;
  margin: 30px 0;
}

.login-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px 10px;
  background-color: var(--primary-light);
  border: 2px solid var(--primary-color);
  border-radius: var(--border-radius);
  cursor: pointer;
  transition: var(--transition);
  text-align: center;
  color: var(--primary-color);
  text-decoration: none;
  position: relative;
  overflow: hidden;
}

.login-btn::before {
  content: "";
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255,255,255,0.4), transparent);
  transition: var(--transition);
}

.login-btn:hover {
  background-color: var(--primary-color);
  color: white;
  transform: translateY(-3px);
  box-shadow: 0 5px 10px rgba(0,0,0,0.1);
}

.login-btn:hover::before {
  left: 100%;
}

.login-btn i {
  font-size: 36px;
  margin-bottom: 10px;
}

.footer {
  margin-top: 30px;
  text-align: center;
  font-size: 12px;
  color: #666;
  padding: 10px;
  border-top: 1px solid #eee;
}

/* 登录消息样式 */
.login-message {
  margin: 20px 0;
  padding: 15px;
  border-radius: var(--border-radius);
  text-align: center;
  font-weight: bold;
  background-color: #f8f9fa;
  border: 1px solid #dee2e6;
}

.login-message.success {
  background-color: #d4edda;
  border-color: #c3e6cb;
  color: #155724;
}

.login-message.error {
  background-color: #f8d7da;
  border-color: #f5c6cb;
  color: #721c24;
}

.login-message i {
  margin-right: 8px;
}

/* 加载状态的按钮样式 */
.login-btn.loading {
  opacity: 0.7;
  cursor: not-allowed;
}

/* 部门选择页样式 */
.department-list {
  margin-top: 20px;
}

/* 业务类型选择页样式 */
.biz-category-list {
  margin-top: 20px;
}

.biz-category-item {
  padding: 15px;
  border-radius: var(--border-radius);
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  transition: var(--transition);
  background-color: white;
  box-shadow: var(--box-shadow);
  border-left: 4px solid var(--success-color);
}

.biz-category-item:hover {
  transform: translateX(5px);
  box-shadow: 0 8px 20px rgba(0,0,0,0.1);
}

.biz-category-item .arrow {
  color: var(--success-color);
  font-size: 16px;
}

.no-data {
  text-align: center;
  padding: 40px 20px;
  color: #666;
}

.no-data i {
  font-size: 48px;
  margin-bottom: 15px;
  color: #ccc;
}

.department-item {
  padding: 15px;
  border-radius: var(--border-radius);
  margin-bottom: 10px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  cursor: pointer;
  transition: var(--transition);
  background-color: white;
  box-shadow: var(--box-shadow);
  border-left: 4px solid var(--primary-color);
}

.department-item:hover {
  transform: translateX(5px);
  box-shadow: 0 8px 20px rgba(0,0,0,0.1);
}

.waiting-number {
  background-color: var(--primary-color);
  color: white;
  padding: 5px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: bold;
  min-width: 80px;
  text-align: center;
}

.waiting-number.low {
  background-color: var(--success-color);
}

.waiting-number.medium {
  background-color: var(--warning-color);
  color: var(--dark-color);
}

.waiting-number.high {
  background-color: var(--danger-color);
}

.waiting-number.loading {
  background-color: #6c757d;
}

.waiting-number i {
  font-size: 10px;
}

/* 叫号信息相关样式 */
.current-number.loading {
  opacity: 0.7;
}

.loading-indicator {
  text-align: center;
  padding: 20px;
}

.loading-indicator i {
  font-size: 24px;
  margin-bottom: 10px;
  color: #1a56a7;
}

.refresh-btn {
  background: none;
  border: 1px solid #1a56a7;
  color: #1a56a7;
  padding: 5px 8px;
  border-radius: 3px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.3s;
}

.refresh-btn:hover:not(:disabled) {
  background-color: #1a56a7;
  color: white;
}

.refresh-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.loading-item {
  justify-content: center;
  font-style: italic;
  color: #666;
}

.user-number {
  background-color: #f0f7ff;
  border: 2px solid #1a56a7;
  font-weight: bold;
  color: #1a56a7;
}

/* 取号相关样式 */
.take-number-message {
  padding: 10px;
  margin: 10px 0;
  border-radius: 5px;
  text-align: center;
  font-weight: bold;
}

.take-number-message.success {
  background-color: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.take-number-message.error {
  background-color: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

.ticket-error {
  background-color: #fff3cd;
  border: 1px solid #ffc107;
  border-radius: 5px;
  padding: 15px;
  margin-top: 15px;
  text-align: center;
}

.ticket-error i {
  color: #856404;
  font-size: 20px;
  margin-bottom: 10px;
}

.ticket-error p {
  margin: 5px 0;
  color: #856404;
  font-size: 14px;
}

/* 打印相关样式 */
.print-message {
  padding: 10px;
  margin: 15px 0;
  border-radius: var(--border-radius);
  text-align: center;
  font-weight: bold;
  font-size: 16px;
}

.print-message.success {
  background-color: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.print-message.error {
  background-color: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

/* 取号成功页样式 */
.ticket {
  background-color: #fff;
  border: 2px dashed var(--primary-color);
  border-radius: var(--border-radius);
  padding: 25px;
  margin: 30px auto;
  max-width: 400px;
  text-align: center;
  box-shadow: var(--box-shadow);
  position: relative;
  overflow: hidden;
}

.ticket::before, .ticket::after {
  content: "••••••••••••••••••••••••••••••••••••••••";
  position: absolute;
  left: 0;
  right: 0;
  color: var(--primary-color);
  font-size: 12px;
  letter-spacing: 2px;
  line-height: 0;
  opacity: 0.3;
}

.ticket::before {
  top: 0;
}

.ticket::after {
  bottom: 0;
}

.ticket h2 {
  color: var(--primary-color);
  margin-bottom: 20px;
  font-size: 22px;
}

.ticket-info {
  margin: 20px 0;
  text-align: left;
  padding: 0 15px;
}

.ticket-info div {
  margin-bottom: 12px;
  display: flex;
  justify-content: space-between;
  border-bottom: 1px dashed #eee;
  padding-bottom: 5px;
}

.ticket-info strong {
  color: var(--primary-color);
}

.btn {
  background-color: var(--primary-color);
  color: white;
  border: none;
  padding: 12px 25px;
  border-radius: var(--border-radius);
  cursor: pointer;
  font-size: 16px;
  margin-top: 20px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  transition: var(--transition);
  box-shadow: 0 3px 5px rgba(0,0,0,0.1);
}

.btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 5px 10px rgba(0,0,0,0.2);
}

.btn:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
  opacity: 0.6;
}

.btn:disabled:hover {
  transform: none;
  box-shadow: 0 3px 5px rgba(0,0,0,0.1);
}

.btn i {
  margin-right: 8px;
}

.btn-secondary {
  background-color: var(--dark-color);
}

.btn-danger {
  background-color: var(--danger-color);
}

.btn-success {
  background-color: var(--success-color);
}

/* 临时建档页样式 */
.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: var(--primary-color);
}

.form-group input {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: var(--border-radius);
  font-size: 16px;
  transition: var(--transition);
}

.form-group input:focus {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 3px rgba(26, 86, 167, 0.2);
  outline: none;
}

.submit-btn {
  background-color: var(--primary-color);
  color: white;
  border: none;
  padding: 12px 20px;
  border-radius: var(--border-radius);
  cursor: pointer;
  font-size: 16px;
  width: 100%;
  margin-top: 15px;
  transition: var(--transition);
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 10px rgba(0,0,0,0.2);
}

/* 黑名单提示页样式 */
.warning-box {
  background-color: #fff3cd;
  border-left: 5px solid var(--warning-color);
  padding: 20px;
  margin: 30px 0;
  border-radius: var(--border-radius);
  box-shadow: var(--box-shadow);
}

.warning-box h2 {
  color: #856404;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.warning-box h2 i {
  margin-right: 10px;
}

.back-btn {
  display: inline-flex;
  align-items: center;
  margin-top: 20px;
  color: var(--primary-color);
  text-decoration: none;
  font-weight: bold;
  transition: var(--transition);
}

.back-btn:hover {
  color: #0d47a1;
}

.back-btn i {
  margin-right: 5px;
}

/* 排队信息页样式 */
.queue-info {
  margin: 20px 0;
}

.current-number {
  background: linear-gradient(135deg, var(--primary-color), #0d47a1);
  color: white;
  padding: 20px;
  border-radius: var(--border-radius);
  text-align: center;
  margin-bottom: 25px;
  box-shadow: var(--box-shadow);
  position: relative;
  overflow: hidden;
}

.current-number::before {
  content: "";
  position: absolute;
  top: -50%;
  right: -50%;
  width: 100%;
  height: 200%;
  background: rgba(255,255,255,0.1);
  transform: rotate(30deg);
}

.current-number h2 {
  margin-bottom: 15px;
  font-size: 20px;
}

.current-number p {
  margin: 5px 0;
}

.current-number .number {
  font-size: 36px;
  font-weight: bold;
  margin: 10px 0;
  display: block;
}

.queue-list {
  margin-top: 20px;
  background-color: white;
  border-radius: var(--border-radius);
  box-shadow: var(--box-shadow);
  overflow: hidden;
}

.queue-item {
  display: flex;
  justify-content: space-between;
  padding: 15px;
  border-bottom: 1px solid #eee;
  transition: var(--transition);
}

.queue-item:last-child {
  border-bottom: none;
}

.queue-item.highlight {
  background-color: var(--primary-light);
  font-weight: bold;
}

.queue-item.highlight span:last-child {
  color: var(--primary-color);
}

/* 临时建档页新增样式 */
.form-group textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 16px;
  font-family: 'Microsoft YaHei', Arial, sans-serif;
  resize: vertical;
  min-height: 80px;
}

.submit-message {
  padding: 10px;
  margin: 10px 0;
  border-radius: 5px;
  text-align: center;
  font-weight: bold;
}

.submit-message.success {
  background-color: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.submit-message.error {
  background-color: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

.submit-btn:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
  opacity: 0.6;
}

.fa-spin {
  animation: fa-spin 2s infinite linear;
}

@keyframes fa-spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 响应式调整 */
@media (max-width: 576px) {
  .login-options {
    grid-template-columns: 1fr 1fr;
  }
  
  .container {
    padding: 10px;
  }
  
  h1 {
    font-size: 24px;
  }
}

/* 页面切换动画 */
.page {
  display: none;
  animation: fadeIn 0.5s;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.active {
  display: block;
}

/* 动画效果 */
@keyframes bounce {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-10px); }
}

.bounce {
  animation: bounce 1s infinite;
}

/* 语音提示区域 */
.voice-notification {
  position: fixed;
  bottom: 20px;
  right: 20px;
  width: 50px;
  height: 50px;
  background-color: var(--primary-color);
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 4px 10px rgba(0,0,0,0.2);
  z-index: 100;
  transition: var(--transition);
}

.voice-notification:hover {
  transform: scale(1.1);
}

.voice-notification.active {
  background-color: var(--danger-color);
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.1); }
  100% { transform: scale(1); }
}

/* 语音提示弹窗 */
.voice-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  opacity: 0;
  pointer-events: none;
  transition: var(--transition);
}

.voice-modal.active {
  opacity: 1;
  pointer-events: auto;
}

.voice-modal-content {
  background-color: white;
  padding: 25px;
  border-radius: var(--border-radius);
  max-width: 400px;
  width: 90%;
  box-shadow: 0 5px 20px rgba(0,0,0,0.2);
  transform: translateY(20px);
  transition: var(--transition);
}

.voice-modal.active .voice-modal-content {
  transform: translateY(0);
}

.voice-modal h3 {
  margin-bottom: 15px;
  color: var(--primary-color);
  display: flex;
  align-items: center;
}

.voice-modal h3 i {
  margin-right: 10px;
}

.voice-options {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

/* 登录页面 */
.login-page {
  max-width: 400px;
  margin: 0 auto;
  padding: 30px 20px;
  background-color: white;
  border-radius: var(--border-radius);
  box-shadow: var(--box-shadow);
}

.login-page h2 {
  text-align: center;
  margin-bottom: 20px;
  color: var(--primary-color);
}

.login-logo {
  text-align: center;
  margin-bottom: 30px;
}

.login-logo i {
  font-size: 50px;
  color: var(--primary-color);
}

/* 数字键盘 */
.numpad-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  margin-top: 20px;
}

.numpad-btn {
  padding: 15px;
  font-size: 20px;
  border: 1px solid #ddd;
  border-radius: var(--border-radius);
  background-color: white;
  cursor: pointer;
  transition: var(--transition);
  text-align: center;
}

.numpad-btn:hover:not(:disabled) {
  background-color: var(--primary-light);
}

.numpad-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.numpad-display {
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: var(--border-radius);
  font-size: 20px;
  text-align: center;
  margin-bottom: 10px;
  background-color: #f8f9fa;
  color: #333;
}

/* 进度条 */
.progress-container {
  width: 100%;
  height: 8px;
  background-color: #e9ecef;
  border-radius: 4px;
  margin: 15px 0;
  overflow: hidden;
}

.progress-bar {
  height: 100%;
  background: linear-gradient(90deg, var(--primary-color), #0d47a1);
  width: 0%;
  transition: width 0.5s ease;
  border-radius: 4px;
}

/* 登录页面样式 */
.login-form {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
}

.login-submit-btn {
  width: 100%;
  padding: 15px;
  background-color: var(--primary-color);
  color: white;
  border: none;
  border-radius: var(--border-radius);
  font-size: 16px;
  cursor: pointer;
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  transition: var(--transition);
}

.login-submit-btn:hover:not(:disabled) {
  background-color: #0f3d7a;
  transform: translateY(-2px);
  box-shadow: 0 5px 10px rgba(0,0,0,0.2);
}

.login-submit-btn:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
  opacity: 0.6;
}

.login-message {
  padding: 10px;
  border-radius: var(--border-radius);
  margin: 15px 0;
  text-align: center;
}

.login-message.success {
  background-color: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.login-message.error {
  background-color: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

/* 人脸识别样式 */
.face-recognition {
  text-align: center;
  padding: 20px;
}

.camera-area {
  margin: 20px 0;
}

.camera-placeholder {
  width: 300px;
  height: 200px;
  border: 2px dashed #ccc;
  border-radius: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 0 auto;
  background-color: #f8f9fa;
  cursor: pointer;
  transition: all 0.3s ease;
}

.camera-placeholder.scanning {
  border-color: #1a56a7;
  background-color: #e3f2fd;
}

.camera-placeholder i {
  font-size: 48px;
  color: #6c757d;
  margin-bottom: 10px;
}

.camera-placeholder.scanning i {
  color: #1a56a7;
}

.face-message {
  padding: 10px;
  border-radius: 4px;
  margin: 15px 0;
  text-align: center;
}

.face-message.success {
  background-color: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.face-message.error {
  background-color: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}
</style>
